package main

import (
	"bblcloud/bblgw"
	"bufio"
	"encoding/json"
	"fmt"
	"os"
	"strings"
)

var client *bblgw.StoreClient

func main() {
	var addr = "127.0.0.1:7800"
	if len(os.Args) > 1 {
		addr = os.Args[1]
	}
	client = bblgw.NewStoreClient(addr, []string{})
	r := bufio.NewReader(os.Stdin)
	var line string
	for {
		os.Stdout.WriteString("#")
		b, _, _ := r.ReadLine()
		line = string(b)
		if strings.TrimSpace(line) == "" {
			continue
		}
		if line == "quit" || line == "q" || line == "exit" {
			break
		}
		do_cmd(strings.Split(line, " "))
	}
}

func do_cmd(args []string) {
	switch args[0] {
	case "add":
		if len(args) != 2 {
			fmt.Println("usage:", "add", "<uuid>")
			return
		}
		err := client.AddVolume(args[1])
		if err != nil {
			fmt.Println("error:", err)
		}
	case "rm":
		if len(args) != 2 {
			fmt.Println("usage:", "rm", "<uuid>")
			return
		}
		err := client.RemoveVolume(args[1])
		if err != nil {
			fmt.Println("error:", err)
		}
	case "addgw":
		if len(args) != 3 {
			fmt.Println("usage:", "add", "<addr> <perm>")
			return
		}
		err := client.AddClient(args[1], args[2])
		if err != nil {
			fmt.Println("error:", err)
		}
	case "rmgw":
		if len(args) != 2 {
			fmt.Println("usage:", "rm", "<addr>")
			return
		}
		err := client.RemoveClient(args[1])
		if err != nil {
			fmt.Println("error:", err)
		}
	case "stat":
		stat, err := client.ClusterStat()
		if err != nil {
			fmt.Println("error:", err)
			return
		}
		b, err := json.MarshalIndent(stat, "", "    ")
		if err != nil {
			fmt.Println("error:", err)
			return
		}
		fmt.Println(string(b))
	default:
		fmt.Println("usage:")
		fmt.Println("add", "<uuid>")
		fmt.Println("  --Add a volume node to the cluster")
		fmt.Println("rm", "<uuid>")
		fmt.Println("  --Remove a volume node from the cluster")
		fmt.Println("stat")
		fmt.Println("  --Print cluster stat")
	}
}
